package br.org.etec.dotcao.mailer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public abstract class Reader<T> {

	private String source;

	public Reader(String source) {
		super();
		this.source = source;
	}
	
	protected abstract void process(String line);
	public abstract T get();

	public Reader<T> read() {
		File file = new File(source);

		if (!file.exists()) {
			throw new RuntimeException("O arquivo informado (" + source + ") não existe...");
		}

		if (!file.canRead()) {
			throw new RuntimeException("O arquivo informado (" + source + ") não pode ser lido...");
		}

		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new FileReader(file));
			String line;

			while ((line = reader.readLine()) != null) {
				process(line);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException("Não foi possível efetuar a leitura do arquivo...", e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		
		return this;
	}

}
